<template>
  <div class="app-container">
    <el-form v-if="showInfo ==='1'||showInfo ==='4'||addInfo==='1'" ref="form" :model="form" :rules="rules" label-width="160px">
      <div style="font-weight: bold;">基本信息</div>
      <el-form-item label="店铺名称" prop="storeCode">
        <el-select :disabled="true" style="width: 850px;" v-model="form.storeCode" placeholder="请选择店铺名称">
          <el-option v-for="dict in allList" :key="dict.storeCode" :label="dict.storeName"
            :value="dict.storeCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input style="width: 850px;" v-model="form.productName" :disabled="showInfo === '4'" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="价格" prop="productShowPrice">
        <el-input style="width: 850px;" v-model="form.productShowPrice" disabled placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="商品详情内容" prop="productDescription">
        <editor style="width: 850px;" :imgDisable="showInfo === '4' ? true : false" v-model="form.productDescription" :min-height="192" />
      </el-form-item>
      <!-- <el-form-item label="产地" prop="fromAddress">
        <el-input style="width: 850px;" v-model="form.fromAddress" placeholder="请输入产地" />
      </el-form-item> -->
      <el-form-item label="产地" prop="fromProvinceId">
        <el-select v-model="form.fromProvinceId" :disabled="showInfo === '4'" clearable placeholder="请选择（必填）"  @change="handleProvinceChange" @clear="handleProvinceClear">
          <el-option v-for="item in privinceList" :key="item.id" :label="item.cname" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="fromCityId" :disabled="showInfo === '4'" clearable placeholder="请选择（选填）" @change="handleCityChange" @clear="handleCityClear">
          <el-option v-for="item in cityList" :key="item.id" :label="item.cname" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="fromCountyId" :disabled="showInfo === '4'" clearable placeholder="请选择（选填）" @change="handleCountyChange" @clear="handleCountyClear">
          <el-option v-for="item in countyList" :key="item.id" :label="item.cname" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品故事" prop="productStory">
        <el-input style="width: 850px;" type="textarea" v-model="form.productStory" :disabled="showInfo === '4'" placeholder="请输入产品故事" />
      </el-form-item>
      <div style="font-weight: bold;">地址信息</div>
      <el-form-item label="发货人" prop="receiveUser">
        <el-input style="width: 850px;" v-model="form.receiveUser" :disabled="showInfo === '4'" placeholder="请输入发货人" />
      </el-form-item>
      <el-form-item label="发货人手机号" prop="receivePhone">
        <el-input style="width: 850px;" v-model="form.receivePhone" :disabled="showInfo === '4'" placeholder="请输入发货人手机号" />
      </el-form-item>
      <el-form-item label="发货地址" prop="provinceCityCountry">
        <el-cascader style="width: 850px;" v-model="form.provinceCityCountry" :disabled="showInfo === '4'" :options="addressXz" :props="propsObj"
          @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="发货地详细地址" prop="productFrom">
        <el-input style="width: 850px;" v-model="form.productFrom" :disabled="showInfo === '4'" placeholder="请输入具体地址" />
      </el-form-item>
      <!-- 退货地详情地址 -->
      <el-form-item label="退货人" prop="returnUser">
        <el-input style="width: 850px;" v-model="form.returnUser" :disabled="showInfo === '4'" placeholder="请输入退货人" />
      </el-form-item>
      <el-form-item label="退货人手机号" prop="returnPhone">
        <el-input style="width: 850px;" v-model="form.returnPhone" :disabled="showInfo === '4'" placeholder="请输入退货人手机号" />
      </el-form-item>
      <el-form-item label="退货地址" prop="backProvinceCityCountry">
        <el-cascader style="width: 850px;" v-model="form.backProvinceCityCountry" :disabled="showInfo === '4'" :options="addressXz" :props="propsObj"
          @change="backHandleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="退货地详细地址" prop="backFrom">
        <el-input style="width: 850px;" v-model="form.backFrom" :disabled="showInfo === '4'" placeholder="请输入退货地详细地址" />
      </el-form-item>
      <div style="font-weight: bold;">其他信息</div>
      <el-form-item label="商品状态" prop="productFlag">
        <el-select style="width: 850px;" v-model="form.productFlag" disabled placeholder="请选择商品状态" clearable>
          <el-option v-for="dict in dict.type.product_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="roles==='admin'" label="商品热度" prop="hotSort">       
        <el-input style="width: 850px;" v-model="form.hotSort" :disabled="showInfo === '4'" placeholder="请输入商品热度" />
      </el-form-item>
    </el-form>
    <el-button v-if="showInfo ==='1'" type="primary" @click="handleBasic('form')">确 定</el-button>

    <el-form v-if="showInfo ==='2'||showInfo ==='4'||addInfo==='1'" ref="form" :model="form" :rules="rules" label-width="160px">
      <div style="font-weight: bold;">销售信息</div>
      <el-form-item label="商品规格" prop="productFlag">
        <el-button icon="el-icon-add" size="mini" :disabled="showInfo === '4'" @click="addGg">添加</el-button>
        <el-table :data="pastInventoryList" style="width: 80%">
          <el-table-column prop="specification" label="规格内容" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.isVisible">{{ scope.row.specification }}</span>
              <el-input type="textarea" v-model.trim="scope.row.specification" v-else size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="salePrice" label="商品金额" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.isVisible">{{ scope.row.salePrice }}</span>
              <el-input v-model="scope.row.salePrice" v-else size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="mainUrl" label="商品图片">
            <template slot-scope="scope">
              <!-- scope.row.isVisible -->
              <!-- scope.row.productFlag==='1' -->
              <div v-if="scope.row.isVisible">
                <el-image style="width: 100px; height: 100px" fit="contain" :src="scope.row.mainUrl"
                  :preview-src-list="[scope.row.mainUrl]">
                </el-image>
              </div>
              <el-upload v-else class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, scope.row, scope.$index,'qa_android_picUrl')"
                :headers="headers" :before-upload="beforeAvatarUpload">
                <el-image v-if="scope.row.mainUrl" style="width: 80px" :src="scope.row.mainUrl"
                  fit="contain"></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="productNumble" label="库存">
            <template slot-scope="scope">
              <span v-if="scope.row.isVisible">{{ scope.row.productNumble }}</span>
              <el-input v-model.number="scope.row.productNumble" v-else size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="productFlag" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.productFlag==='0'||scope.row.productFlag==='1'" size="medium"
                :type="scope.row.productFlag === '1' ? 'success' : 'info'">
                {{scope.row.productFlag === '1' ? '已启用' : scope.row.productFlag === '0' ? '未启用' : ''}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230px" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <div v-if="scope.row.isAdd">
                <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleSave(scope.$index,scope.row,'01')">保存</el-button>
              </div>
              <div v-else>
                <div v-if="scope.row.productFlag==='1'">
                  <!-- 在这里在加一层判断 -->
                  <!-- 点击编辑后 变成保存 -->
                  <div v-if="scope.row.isVisible">
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handlePause(scope.$index,scope.row)">停用</el-button>
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
                  </div>
                  <div v-else>
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleSave(scope.$index,scope.row,'02')">保存</el-button>
                  </div>
                </div>
                <div v-else-if="scope.row.productFlag==='0'">
                  <div v-if="scope.row.isVisible">
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleOpen(scope.$index,scope.row)">启用</el-button>
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
                    <!-- <el-button style="color: #888;" v-if="pastInventoryList.length==1" size="mini"
                      type="text">删除</el-button> -->
                    <el-button size="mini" :disabled="showInfo === '4'" type="text"
                      @click="handleDelete(scope.$index,scope.row)">删除</el-button>
                  </div>
                  <div v-else>
                    <el-button size="mini" :disabled="showInfo === '4'" type="text" @click="handleSave(scope.$index,scope.row,'03')">保存</el-button>
                  </div>
                </div>
                <div v-else>

                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-button v-if="showInfo ==='2'" type="primary" @click="handleSubmit()">确 定</el-button>

    <el-form v-if="showInfo ==='3'||showInfo ==='4'||addInfo==='1'" ref="form" :model="form" :rules="rules" label-width="160px">
      <div style="font-weight: bold;">商品图片</div>
      <el-form-item v-if="showInfo ==='3'||addInfo==='1'" label="商品主图" prop="productManUrl">
        <el-upload style="width: 300px;" :limit="1" :action="uploadUrl" :headers="headers" list-type="picture"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess"
          :file-list="productPicList">
          <el-button :disabled="productPicList&&productPicList.length>0 ? true : false" size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-else label="商品主图" prop="productManUrl">
        <div style="display: flex;flex-wrap: wrap;">
              <div v-for="(item,index) in productPicList" :key="index">
              <el-image style="width: 200px; height: 100px" :preview-src-list="productPicList.map(v=>v.url)" :src="item.url"
                fit="contain"></el-image>
            </div>
            </div>
      </el-form-item>
      <el-form-item v-if="showInfo ==='3'||addInfo==='1'"  label="商品详情页主图" prop="productManUrl">
        <el-upload style="width: 300px;" :limit="6" multiple :action="uploadUrl" :headers="headers" list-type="picture"
          :on-preview="handlePictureCardPreviewDetails" :on-remove="handleRemoveDetails"
          :on-success="handleSuccessDetails" :file-list="productPicDetailsList">
          <el-button :disabled="productPicDetailsList&&productPicDetailsList.length>5 ? true : false" size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-else label="商品详情页主图" prop="productManUrl">
        <div style="display: flex;flex-wrap: wrap;">
              <div v-for="(item,index) in productPicDetailsList" :key="index">
              <el-image style="width: 200px; height: 100px" :preview-src-list="productPicDetailsList.map(v=>v.url)"  :src="item.url"
                fit="contain"></el-image>
            </div>
            </div>
      </el-form-item>
    </el-form>
    <el-button v-if="showInfo ==='3'" type="primary" @click="handlePicSubmit()">确 定</el-button>
    <el-button v-if="addInfo ==='1'" type="primary" @click="addSubmit()">确 定</el-button>
  </div>
</template>
<script>
  import {
    getToken
  } from "@/utils/auth";
  import {
    productCodeEditDetails,
    productinfoDisplay,
    onlinestoreAllList,
    productinfoRelease,
    getAddressInfo
  } from "@/api/store/productinfo";

  import {
    getOrderAddress,
  } from "@/api/system/user";

  export default {
    name: "productinfoDetails",
    dicts: ['product_flag'],
    data() {
      return {
        detailsFileList: [],
        // 表单参数
        form: {},
        productCode: '',
        pastInventoryList: [],
        pastInventoryListDel: [],
        productInfo: {},
        productPicList: [],
        productPicDetailsList: [],
        productPicListDel: [],
        productPicDetailsListDel: [],
        productPicListParams: [],
        productPicDetailsListParams: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        fileList: [],
        // customHeaders: {
        //   Authorization: "Bearer " + getToken()
        // },
        uploadUrl: process.env.VUE_APP_BASE_API + "/file/upload/oss", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        rules: {
          // storeCode
          storeCode: [{
            required: true,
            message: '请选择店铺名称',
            trigger: 'change'
          }],
          productName: [{
            required: true,
            message: '请输入',
            trigger: 'change'
          }, {
            validator: this.validateDescription1,
            trigger: 'blur'
          }],
          receiveUser: [{
            required: true,
            message: '请输入发货人',
            trigger: 'change'
          }],
          receivePhone: [{
            required: true,
            message: '请输入发货人手机号',
            trigger: 'change'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }],
          provinceCityCountry: [{
            required: true,
            message: '请选择发货地址',
            trigger: 'change'
          }],
          productFrom: [{
            required: true,
            message: '请输入发货地详细地址',
            trigger: 'change'
          }, {
            validator: this.validateDescription2,
            trigger: 'blur'
          }],
          returnUser: [{
            required: true,
            message: '请输入退货人',
            trigger: 'change'
          }],
          fromProvinceId: [{
            required: true,
            message: '请选择产地',
            trigger: 'change'
          }],
          productStory: [{
            validator: this.validateDescription3,
            trigger: 'blur'
          }],
          returnPhone: [{
            required: true,
            message: '请输入退货人手机号',
            trigger: 'change'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }],
          backProvinceCityCountry: [{
            required: true,
            message: '请选择退货地址',
            trigger: 'change'
          }],
          backFrom: [{
            required: true,
            message: '请输入退货地详细地址',
            trigger: 'change',
          }, {
            validator: this.validateDescription2,
            trigger: 'blur'
          }],
          productFlag: [{
            required: true,
            message: '请选择商品状态',
            trigger: 'change'
          }],
          productDescription: [{
            required: true,
            message: '商品详情内容',
            trigger: 'change'
          }]
        },
        //
        showInfo: '',
        addInfo: '',
        // 基本信息编辑  handleBasicInfo
        // 规格编辑  handleSpecs
        // 商品图片编辑  handleProductImage
        allList: [],
        addressXz: [],
        propsObj: {
          label: 'text',
          value: 'value',
          option: 'children',
        },
        i: 0,
        uploadOptions: {
          // el-upload 的其他配置项
          action: process.env.VUE_APP_BASE_API + "/file/upload/oss", // 示例上传地址
          onSuccess: (response, file, fileList, rowIndex) => {
            // 上传成功后的处理函数
            console.log(`第${rowIndex}条数据上传成功`);
          }
        },
        dialogVisible: false,
        dialogImageUrl: '',
        privinceList: [],
        cityList: [],
        countyList: [],
        cdValue: '',
        provinceShouldIgnoreNextChange: false,
        cityShouldIgnoreNextChange: false,
        countyShouldIgnoreNextChange: false,
        fromProvinceId:null,
        fromCityId:"",
        fromCountyId:"",
        fromProvinceName:'',
        fromCityName:'',
        fromCountyName:'',
        roles: this.$store.getters.roles[0] 
      }
    },
    created() {
      const productCode = this.$route.params && this.$route.params.productCode;
      const flag = this.$route.params && this.$route.params.flag;
      const isAdd = this.$route.params && this.$route.params.isAdd;
      if (productCode) {
        console.log(productCode, 'productCode')
        this.getDetails(productCode)
      }
      if (flag) {
        console.log('2222222222222222',flag)
        console.log(flag, 'flag')
        this.showInfo = flag
      }
      if (isAdd) {
        console.log(isAdd, '================')
        this.addInfo = isAdd
        console.log(this.addInfo, '==============11111111111')
        console.log(isAdd, 'isAdd')
      }
      this.getonlinestoreAllList()
      this.getOrderAddress()
    },
    methods: {
      validateDescription1(rule, value, callback) {
        if (value&&value.length > 60) {
          callback(new Error('输入内容不能超过60个字'));
        } else {
          callback();
        }
      },
      validateDescription2(rule, value, callback) {
        if (value&&value.length > 120) {
          callback(new Error('输入内容不能超过120个字'));
        } else {
          callback();
        }
      },
      validateDescription3(rule, value, callback) {
        if (value&&value.length > 200) {
          callback(new Error('输入内容不能超过200个字'));
        } else {
          callback();
        }
      },
      handlePreview(file) {
        // 当前图片预览
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      getUploadData(row) {
        return {
          rowIndex: row.id,
        };
      },
      // 停用
      // "productFlag": "1", //库存启用（0-未启用 1-已启用）
      handlePause(index, row) {
        let arr = this.pastInventoryList.map(item => item.productFlag==='1');
        let newArr = arr.filter(value => value===true)
        if(newArr.length === 1){
          this.$modal.msgError('商品最后一项规格必须保持启用状态');
          return
        }
        this.$set(this.pastInventoryList, index, {
          ...this.pastInventoryList[index],
          productFlag: '0'
        });
      },
      handleOpen(index, row) {
        this.$set(this.pastInventoryList, index, {
          ...this.pastInventoryList[index],
          productFlag: '1'
        });
      },
      // 删除
      handleDelete(index, row) {
        this.pastInventoryListDel.push(row)
        // let arr = this.pastInventoryList.map(item => item.productFlag==='1');
        // let newArr = arr.filter(value => value===true)
        if(this.pastInventoryList.length === 1){
          this.$modal.msgError('商品最后一项规格不允许删除');
          return
        }
        this.pastInventoryList.splice(index, 1)
      },
      // 保存
      handleSave(index, row, flag) {
        // 规格内容specification
        // 商品金额salePrice
        // 商品图片mainUrl
        // 库存productNumble
        //
        if (!row.specification) {
          this.$modal.msgError('规格内容不能为空');
          return
        }
        if (!/^.{1,60}$/.test(row.specification)) {
          this.$modal.msgError('规格内容60字以内');
          return
        }
        if (!row.salePrice) {
          this.$modal.msgError('商品金额不能为空');
          return
        }
        if (!/^(\d+|\d+\.\d+)$/.test(row.salePrice)) {
          this.$modal.msgError('商品金额只能输入整数或小数');
          return
        }

        if (!/^\d+(\.\d{1,2})?$/.test(row.salePrice)) {
          this.$modal.msgError('请输入正确的小数点后两位数字');
          return
        }

        if (!row.mainUrl) {
          this.$modal.msgError('商品图片不能为空');
          return
        }
        if (!row.productNumble) {
          this.$modal.msgError('库存不能为空');
          return
        }
        if (flag == '01') {
          this.$set(this.pastInventoryList, index, {
            ...this.pastInventoryList[index],
            isVisible: true,
            productFlag: '1',
            isAdd: false,
          });
        } else {
          this.$set(this.pastInventoryList, index, {
            ...this.pastInventoryList[index],
            isVisible: true,
            isAdd: false,
          });
        }

      },
      getCurrentDateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // return `${year}-${month}-${day} ${hours}:${minutes}`;
      },

      handleBasic(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let result = this.allList.find((element) => element.storeCode === this.form.storeCode);
            console.log(result,'result')
            let params = {
              "storeName": result && result.storeName ? result.storeName : '', //店铺名称
              "storeCode": this.form.storeCode, //店铺编码
              "productCode": this.form.productCode,
              "productName": this.form.productName, //商品名称
              "productManUrl": this.form.productManUrl, //商品主图
              "productShowPrice": this.form.productShowPrice, //价格
              "productDescription": this.form.productDescription, //商品详情内容
              "productFlag": this.form.productFlag, //商品状态（1-立即上架 2-放入仓库 字典product_flag）
              "provinceId": this.form.provinceId, //发货省
              "cityId": this.form.cityId, //发货市
              "countyId": this.form.countyId, //发货县
              "productFrom": this.form.productFrom, //发货地详细地址
              "receiveUser": this.form.receiveUser, //发货人
              "receivePhone": this.form.receivePhone, //发货人手机号
              "backProvinceId": this.form.backProvinceId, //退货省
              "backCityId": this.form.backCityId, //退货市
              "backCountyId": this.form.backCountyId, //退货县
              "backFrom": this.form.backFrom, //退货详细地址
              "returnUser": this.form.returnUser, //退货接收人
              "returnPhone": this.form.returnPhone, //退货接收联系方式
              "fromAddress": this.fromProvinceName + this.fromCityName + this.fromCountyName, //产地
              "productStory": this.form.productStory, //产品故事
              "hotSort": this.form.hotSort, //商品热度
              "saleSort": this.form.saleSort, //已售数量
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "fromProvinceId":this.form.fromProvinceId,
              "fromCityId":this.fromCityId,
              "fromCountyId":this.fromCountyId
            }
            let data = {
              productInfo: params
            }
            productCodeEditDetails(data).then(response => {
              if (response.code == '200') {
                this.$modal.msgSuccess('修改成功');
                this.$store.dispatch('/productinfoDetails/shop-data/infoDetails', this.$route)
                this.$router.go(-1)
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });



      },
      // 商品规格保存
      handleSubmit() {
        // this.pastInventoryListDel.forEach(item=>{
        //   item.delFlag = '2'
        // })
        let pastInventoryListDelNew = this.pastInventoryListDel.map(item => {
          return Object.assign({}, {
            inventoryId: item.inventoryId ? item.inventoryId : '',
            specification: item.specification,
            salePrice: item.salePrice,
            productNumble: item.productNumble,
            productFlag: item.productFlag,
            mainUrl: item.mainUrl,
            crTime: item.inventoryId ? '' : this.getCurrentDateTime(),
            upTime: item.inventoryId ? this.getCurrentDateTime() : this.getCurrentDateTime(),
            "productCode": this.$route.params.productCode,
            'delFlag':'2'
          })
        })

        const isBlob = this.pastInventoryList.some((item) => !item.isVisible)
        if (isBlob) {
          this.$modal.msgError('商品规格请保存后再提交');
          return
        }

        // 新增  取本地时间
        // 修改  取本地时间（只传修改时间）
        let params = this.pastInventoryList.map(item => {
          return Object.assign({}, {
            inventoryId: item.inventoryId ? item.inventoryId : '',
            specification: item.specification,
            salePrice: item.salePrice,
            productNumble: item.productNumble,
            productFlag: item.productFlag,
            mainUrl: item.mainUrl,
            crTime: item.inventoryId ? '' : this.getCurrentDateTime(),
            upTime: item.inventoryId ? this.getCurrentDateTime() : this.getCurrentDateTime(),
            "productCode": this.$route.params.productCode,
            'delFlag':'0'
          })
        })
        let data = {
          // pastInventoryList: params
          pastInventoryList: [...params,...pastInventoryListDelNew]
        }
        productCodeEditDetails(data).then(response => {
          if (response.code == '200') {
            this.$modal.msgSuccess('修改成功');
            this.$store.dispatch('/productinfoDetails/shop-data/infoDetails', this.$route)
            this.$router.go(-1)
          }
        });
      },
      // 商品图片保存
      handlePicSubmit() {

        if(this.productPicList.length===0){
          this.$modal.msgError('商品主图必填');
          return
        }
        if(this.productPicDetailsList.length===0){
          this.$modal.msgError('商品详情图必填');
          return
        }

        let productPicListDelNew = this.productPicListDel.map(item => {
          return Object.assign({}, {
              "productId": item.productId ? item.productId : '',
              "productUrl": item.url, //图片地址
              "urlSort": '', //图片排序
              "picType": "0", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "productCode": this.$route.params.productCode,
              "delFlag":'2'
          })
        })

        let productPicDetailsListDelNew = this.productPicDetailsListDel.map(item => {
          return Object.assign({}, {
              "productId": item.productId ? item.productId : '',
              "productUrl": item.url, //图片地址
              "urlSort": '', //图片排序
              "picType": "1", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "productCode": this.$route.params.productCode,
              "delFlag":'2'
          })
        })

        let newList1 = []
        let newList2 = []

        // 新增  取本地时间
        // 修改  取本地时间（只传修改时间）

        this.productPicList.forEach(item => {
          if (item.response) {
            newList1.push({
              "productId": '',
              "productUrl": item.response.data[0].url, //图片地址
              "urlSort": '', //图片排序
              "picType": "0", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "productCode": this.$route.params.productCode,
              "delFlag":'0'
            })
          } else {
            newList1.push({
              "productId": item.productId,
              "productUrl": item.url, //图片地址
              "urlSort": item.urlSort, //图片排序
              "picType": item.picType, //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": item.picFlag, //图片标识（传1）
              // "crTime": item.crTime, //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "delFlag":'0'
            })
          }
        })

        this.productPicDetailsList.forEach(item => {
          if (item.response) {
            newList2.push({
              "productId": '',
              "productUrl": item.response.data[0].url, //图片地址
              "urlSort": '', //图片排序
              "picType": "1", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "productCode": this.$route.params.productCode,
              "delFlag":'0'
            })
          } else {
            newList2.push({
              "productId": item.productId,
              "productUrl": item.url, //图片地址
              "urlSort": item.urlSort, //图片排序
              "picType": item.picType, //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": item.picFlag, //图片标识（传1）
              // "crTime": item.crTime, //创建时间
              "upTime": this.getCurrentDateTime(), //更新时间
              "delFlag":'0'
            })
          }
        })
        let list = []
        list = [...newList1, ...newList2,...productPicListDelNew,...productPicDetailsListDelNew]
        let data = {
          productPicList: list
        }
        productCodeEditDetails(data).then(response => {
          if (response.code == '200') {
            this.$modal.msgSuccess('修改成功');
            this.$store.dispatch('/productinfoDetails/shop-data/infoDetails', this.$route)
            this.$router.go(-1)
          }
        });
      },

      addSubmit1() {
        let params = {
          "storeName": this.form.storeName, //店铺名称
          "storeCode": this.form.storeCode, //店铺编码
          "productCode": this.form.productCode,
          "productName": this.form.productName, //商品名称
          "productManUrl": this.form.productManUrl, //商品主图
          "productShowPrice": this.form.productShowPrice, //价格
          "productDescription": this.form.productDescription, //商品详情内容
          "productFlag": this.form.productFlag, //商品状态（1-立即上架 2-放入仓库 字典product_flag）
          "provinceId": this.form.provinceId, //发货省
          "cityId": this.form.cityId, //发货市
          "countyId": this.form.countyId, //发货县
          "productFrom": this.form.productFrom, //发货地详细地址
          "receiveUser": this.form.receiveUser, //发货人
          "receivePhone": this.form.receivePhone, //发货人手机号
          "backProvinceId": this.form.backProvinceId, //退货省
          "backCityId": this.form.backCityId, //退货市
          "backCountyId": this.form.backCountyId, //退货县
          "backFrom": this.form.backFrom, //退货详细地址
          "returnUser": this.form.returnUser, //退货接收人
          "returnPhone": this.form.returnPhone, //退货接收联系方式
          "fromAddress": this.form.fromAddress, //产地
          "productStory": this.form.productStory, //产品故事
          "hotSort": this.form.hotSort, //商品热度
          "saleSort": this.form.saleSort, //已售数量
          "crTime": this.getCurrentDateTime(), //创建时间
          "upTime": this.getCurrentDateTime() //更新时间
        }
        // 规格
        let pastInventoryList = this.pastInventoryList.map(item => {
          return Object.assign({}, {
            inventoryId: item.inventoryId,
            specification: item.specification,
            salePrice: item.salePrice,
            productNumble: item.productNumble,
            productFlag: item.productFlag,
            crTime: this.getCurrentDateTime(),
            upTime: this.getCurrentDateTime(),
          })
        })
        // 主图和详情图
        let newList1 = []
        let newList2 = []
        this.productPicList.forEach(item => {
          if (item.response) {
            newList1.push({
              "productId": '',
              "productUrl": item.response.data[0].url, //图片地址
              "urlSort": 1, //图片排序
              "picType": "0", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime() //更新时间
            })
          } else {
            newList1.push({
              "productId": item.productId,
              "productUrl": item.url, //图片地址
              "urlSort": item.urlSort, //图片排序
              "picType": item.picType, //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": item.picFlag, //图片标识（传1）
              "crTime": item.crTime, //创建时间
              "upTime": this.getCurrentDateTime() //更新时间
            })
          }
        })
        this.productPicDetailsList.forEach(item => {
          if (item.response) {
            newList2.push({
              "productId": '',
              "productUrl": item.response.data[0].url, //图片地址
              "urlSort": 1, //图片排序
              "picType": "1", //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": "1", //图片标识（传1）
              "crTime": this.getCurrentDateTime(), //创建时间
              "upTime": this.getCurrentDateTime() //更新时间
            })
          } else {
            newList2.push({
              "productId": item.productId,
              "productUrl": item.url, //图片地址
              "urlSort": item.urlSort, //图片排序
              "picType": item.picType, //图片类型（0-商品主图 1-商品详情页主图）
              "picFlag": item.picFlag, //图片标识（传1）
              "crTime": item.crTime, //创建时间
              "upTime": this.getCurrentDateTime() //更新时间
            })
          }
        })
        let list = []
        list = [...newList1, ...newList2]
        let data = {
          productInfo: params,
          pastInventoryList: pastInventoryList,
          productPicList: list,
        }
        productinfoRelease(data).then(response => {
          if (response.code == '200') {
            this.$modal.msgSuccess('新增成功');
          }
        });
      },
      // 编辑
      handleEdit(index, row) {
        this.$set(this.pastInventoryList, index, {
          ...this.pastInventoryList[index],
          isVisible: false
        });
      },
      backHandleChange(value) {
        this.form.backProvinceId = value[0]
        this.form.backCityId = value[1]
        this.form.backCountyId = value[2]
        console.log(value);
      },
      handleChange(value) {
        this.form.provinceId = value[0]
        this.form.cityId = value[1]
        this.form.countyId = value[2]
        console.log(value);
      },
      getOrderAddress() {
        getOrderAddress().then(response => {
          if (response.code == '200') {
            console.log(response, '测试')
            this.addressXz = JSON.parse(JSON.parse(response.data))
          }
        });
      },
      getonlinestoreAllList() {
        console.log(111)
        onlinestoreAllList().then(response => {
          this.allList = response.data
        });
      },
      getDetails(productCode) {
        productinfoDisplay(productCode).then(async res => {
          if (res.code == '200') {
            this.pastInventoryList = res.data.pastInventoryList
            this.pastInventoryList.forEach(v => {
              v.isVisible = true
              v.isAdd = false
            })
            this.form = res.data.productInfo
            this.privinceList = []
            let res1 = await getAddressInfo({ctype:'1',parentId:0})            
            this.privinceList = res1.data
            let dataProvince = this.privinceList.filter(v=>v.id===this.form.fromProvinceId)[0]
            this.fromProvinceName = dataProvince&& dataProvince.cname ? dataProvince.cname : ''
            // if(this.form.fromProvinceId){
            //   this.privinceList = []
            //   let res1 = await getAddressInfo({ctype:'1',parentId:0})            
            //   this.privinceList = res1.data
            //   let dataProvince = this.privinceList.filter(v=>v.id===this.form.fromProvinceId)[0]
            //   console.log(dataProvince,'dataProvince')
            //   this.fromProvinceName = dataProvince&& dataProvince.cname ? dataProvince.cname : ''
            // }
            if(this.form.fromProvinceId){
              this.cityList = []
              let res2 = await getAddressInfo({ctype:'2',parentId:this.form.fromProvinceId})            
              this.cityList = res2.data
              this.fromCityId = this.form.fromCityId
              let dataCity = this.cityList.filter(v=>v.id===this.fromCityId)[0]
              console.log(dataCity,'dataCity')
              this.fromCityName = dataCity&& dataCity.cname ?  dataCity.cname : ''
            }

            if(this.form.fromProvinceId&&this.form.fromCityId){
              this.countyList = []    
              let res3 =await getAddressInfo({ctype:'3',parentId:this.form.fromCityId})
              this.countyList = res3.data
              this.fromCountyId = this.form.fromCountyId

              let dataCounty = this.countyList.filter(v=>v.id===this.fromCountyId)[0]
              console.log(dataCounty,'dataCounty')
              this.fromCountyName = dataCounty&& dataCounty.cname ?  dataCounty.cname : ''
            }
            this.form.provinceCityCountry = [this.form.provinceId, this.form.cityId, this.form.countyId]
            this.form.backProvinceCityCountry = [this.form.backProvinceId, this.form.backCityId, this.form
              .backCountyId
            ]
            let picList = res.data.productPicList

            // 商品主图"picType": "1", //图片类型（0-商品主图 1-商品详情页主图）
            this.productPicList = picList.filter(v => v.picType === '0').map(item => {
              return Object.assign({}, {
                name: '',
                url: item.productUrl,
                isFlag: true,
                productId: item.productId,
                urlSort: item.urlSort,
                crTime: item.crTime,
                upTime: item.upTime,
                picFlag: item.picFlag,
                picType: item.picType
              })
            })
            this.productPicListParams = JSON.parse(JSON.stringify(this.productPicList))
            // 商品详情页主图
            this.productPicDetailsList = picList.filter(v => v.picType === '1').map(item => {
              return Object.assign({}, {
                name: '',
                url: item.productUrl,
                isFlag: true,
                productId: item.productId,
                urlSort: item.urlSort,
                crTime: item.crTime,
                upTime: item.upTime,
                picFlag: item.picFlag,
                picType: item.picType
              })
            })
            this.productPicDetailsListParams = JSON.parse(JSON.stringify(this.productPicDetailsList))
            console.log(this.productPicList, '商品主图')
            console.log(this.productPicDetailsList, '商品详情页主图')
          }
        });
      },
      addGg() {
        this.pastInventoryList = [
          ...this.pastInventoryList,
          {
            id: `${this.i}`,
            specification: '',
            salePrice: '',
            mainUrl: '',
            productNumble: '',
            productFlag: '1',
            isVisible: false,
            isAdd: true
          }
        ];
      },
      reset() {
        this.form = {
          storeCode: null,
          productName: null,
          productManUrl: null,
          productShowPrice: null,
          productFlag: null,
          provinceId: null,
          cityId: null,
          countyId: null,
          productFrom: null,
          hotSort: null,
          fromAddress: null,
          productStory: null,
          saleSort: null,
          productDescription: null,
          backProvinceId: null,
          backCityId: null,
          backCountyId: null,
          backFrom: null,
          returnUser: null,
          returnPhone: null,
          receiveUser: null,
          receivePhone: null,
          fromProvinceId: '',
        };
        this.fromCityId = '',
        this.fromCountyId= '',
        this.fromProvinceName='',
        this.fromCityName= '',
        this.fromCountyName=''
        this.resetForm("form");
      },
      // 商品主图
      handleRemove(file, fileList) {
        this.productPicListDel.push(file)
        this.productPicList = fileList
        // let list = fileList
        // // 回显的
        // let oldList = list.filter(v => v.isFlag)
        // // 新增的
        // let newList = list.filter(v => !v.isFlag)
        // let newListNew = []
        // newList.forEach(item=>{
        //   newListNew = [...newListNew,...item.response.data]
        // })
        // let allList = []
        // allList = [...oldList,...newListNew]
        // this.productPicListParams = allList
      },
      handlePictureCardPreview(file) {},
      handleSuccess(response, file, fileList) {
        this.productPicList = fileList
        // let list = fileList
        // // 回显的
        // let oldList = list.filter(v => v.isFlag)
        // // 新增的
        // let newList = list.filter(v => !v.isFlag)
        // let newListNew = []
        // newList.forEach(item=>{
        //   newListNew = [...newListNew,...item.response.data]
        // })
        // let allList = []
        // allList = [...oldList,...newListNew]
        // this.productPicListParams = allList
      },

      // 商品详情页主图
      handlePictureCardPreviewDetails(file, fileList) {
        console.log(file, fileList);
      },
      handleSuccessDetails(response, file, fileList) {
        this.productPicDetailsList = fileList
        // let list = fileList
        // // 回显的
        // let oldList = list.filter(v => v.isFlag)
        // // 新增的
        // let newList = list.filter(v => !v.isFlag)
        // let newListNew = []
        // newList.forEach(item=>{
        //   newListNew = [...newListNew,...item.response.data]
        // })
        // let allList = []
        // allList = [...oldList,...newListNew]
        // this.productPicDetailsListParams = allList
      },
      handleRemoveDetails(file, fileList) {
        this.productPicDetailsListDel.push(file)
        this.productPicDetailsList = fileList
        // let list = fileList
        // // 回显的
        // let oldList = list.filter(v => v.isFlag)
        // // 新增的
        // let newList = list.filter(v => !v.isFlag)
        // let newListNew = []
        // newList.forEach(item=>{
        //   newListNew = [...newListNew,...item.response.data]
        // })
        // let allList = []
        // allList = [...oldList,...newListNew]
        // this.productPicDetailsListParams = allList
      },
      handleAvatarSuccess(res, file, fileList, row, index, col) {
        console.log(res, file, fileList, row, index, col)
        this.$message.success('上传成功');
        // this.$set(this.form.events[row.event_index], col, fileList);

        this.$set(this.pastInventoryList, index, {
          ...this.pastInventoryList[index],
          mainUrl: file.response.data[0].url
        });
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        // const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return isJPG && isLt2M;
      },
      getAddressInfo(ctype,parentId) {
        let params = {
          ctype:ctype,
          parentId:parentId
        }
        // 回显规格接口
        getAddressInfo(params).then(response => {
          if (response.code = '200') {
            if(ctype==='1'){
              this.privinceList = response.data
            } else if(ctype==='2'){
              this.cityList = []
              this.countyList = []
              this.fromCityId = '';
              this.fromCountyId = '';
              this.fromCityName = '';
              this.fromCountyName = '';
              this.cityList = response.data
             
            } else if(ctype ==='3'){
              this.countyList = []
              this.fromCountyId = '';
              this.fromCountyName = '';
              this.countyList = response.data
            } else {
            }       
          }
        });
      },
      // 省
      handleProvinceChange(value) {
        let data = this.privinceList.filter(v=>v.id===value)[0]
        console.log(data,'省')
        this.fromProvinceName = data&&data.cname ? data.cname : ''
        this.$nextTick(() => {
          if (!this.provinceShouldIgnoreNextChange) {
            this.getAddressInfo('2',data.id)
          } else {
            this.provinceShouldIgnoreNextChange = false;
          }
        })
      },
      handleProvinceClear() {
        this.provinceShouldIgnoreNextChange = true;
        this.form.fromProvinceId = '';
        this.fromCityId = '';
        this.fromCountyId = '';
        this.fromProvinceName = '';
        this.fromCityName = '';
        this.fromCountyName = '';
        this.cityList = []
        this.countyList = []
      },
      // 市
      handleCityChange(value) {
        console.log(value,'value')
        let data = this.cityList.filter(v=>v.id===value)[0]
        console.log(data,'市')
        this.fromCityName = data&&data.cname ? data.cname : ''
        this.$nextTick(() => {
          if (!this.cityShouldIgnoreNextChange) {
            this.getAddressInfo('3',data.id)
          } else {
            this.cityShouldIgnoreNextChange = false;
          }
        })
      },
      handleCityClear() {
        this.cityShouldIgnoreNextChange = true;
        this.fromCityId = '';
        this.fromCountyId = '';
        this.fromCityName = '';
        this.fromCountyName = '';
        this.countyList = []
      },
      // 县
      handleCountyChange(value) {
        let data = this.countyList.filter(v=>v.id===value)[0]
        this.fromCountyName = data&&data.cname ? data.cname : ''
        this.$nextTick(() => {
          if (!this.countyShouldIgnoreNextChange) {
            this.getAddressInfo('4',data.id)
          } else {
            this.countyShouldIgnoreNextChange = false;
          }
        })
      },
      handleCountyClear() {
        this.countyShouldIgnoreNextChange = true;
        this.fromCountyId = '';
        this.fromCountyName = '';
      },
    }
  }
</script>
<style>
  .multi-line-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    /* 显示的行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    max-height: 3.0em;
    /* 行高和这个值相乘就是最大高度 */
  }

  .image-list {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    display: flex;
    flex-wrap: wrap;

    li {
      width: 150px;
      height: 150px;
      margin-right: 3%;
      position: relative;

      span {
        position: absolute;
        right: 0px;
        top: 0px;
        cursor: pointer;
      }
    }
  }
</style>
